package iha.standard;

import iha.framework.*;
import java.util.*;

public class FindItem implements IFindItem
{
    private IItemCache cache;
    private ISearchSubSupplier db;
    private int expiretime;

    public FindItem(IItemCache cache, ISearchSubSupplier db)
    {
	this.cache = cache;
	this.db = db;
	this.expiretime = 24;
    }

    private Date getExpireCutoff()
    {
	Date now = new Date();
	long expireInMillis = expiretime * 60 * 60 * 1000;
	return new Date(now.getTime()-expireInMillis);
    }

    public LinkedList<IItem> LookUpItem(long partnumber, String description)
    {
	LinkedList<IItem> res = new LinkedList<IItem>();
	LinkedList<IItem> tooOld = new LinkedList<IItem>();
	LinkedList<IItem> cachehit = cache.LookUpItem(partnumber, description);

	for (IItem i : cachehit)	    
	    if (i.getHit().after(getExpireCutoff()))
		res.add(i);
	    else
		tooOld.add(i);

	cache.RemoveItems(tooOld);

	if (res.size() > 0)
	    return res;
	else
	    {
		LinkedList<IItem> dbhit = db.LookUpItem(partnumber, description);	

		// possibly call setHit on each item with a now date object
		// prior to adding them to the cache.
		// the assignment doesnt specify if this has been done or not, 
		// but it does not appear in the sequence diagrams, so we choose to not to do it.
		
		cache.AddItems(dbhit);
		return dbhit;
	    }
    }

    public void SetCacheExpireTime(int hours)
    {
	this.expiretime = hours;
    }
}